﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Transactions;
using BaseLinQ.DataContex;
using Core;

namespace Module
{
    public class DonViLogic
    {
        public string _conn = ConfigurationSettings.AppSettings["ConnectString"];
        public List<tbl_Donvi> lstDONVI = null;
        public List<tbl_Donvi> lstDONVITmp = null;

        public List<tbl_Donvi> DonViSelectAll()
        {
            try
            {
                using (var trans = new TransactionScope())
                {
                    var db = new RBACDataContext(_conn);
                    List<tbl_Donvi> lstDonVi = (from dv in db.tbl_Donvis select dv).ToList<tbl_Donvi>();

                    trans.Complete();
                    return lstDonVi;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public List<tbl_Donvi> ListTreeDonVi(long ParentID)
        {
            var db = new RBACDataContext(_conn);
            List<tbl_Donvi> lstDonVi = null;
            string strPrefix = "";
            try
            {
                {
                    lstDonVi = (from dv in db.tbl_Donvis
                                where dv.iParent_ID == ParentID && dv.Status == true
                                select dv).OrderBy(e => e.sTenDonVi).ToList<tbl_Donvi>();

                    if (lstDonVi != null && lstDonVi.Count > 0)
                    {
                        lstDONVITmp = (from dv_tmp in db.tbl_Donvis where dv_tmp.Status == true select dv_tmp).ToList<tbl_Donvi>();

                        lstDONVI = new List<tbl_Donvi>();
                        int i = 0;
                        foreach (tbl_Donvi itemDonVi in lstDonVi)
                        {
                            i += 1;
                            strPrefix = i + "";
                            itemDonVi.sTenDonVi = "<b style='color:red;'>" + strPrefix + ".</b>&nbsp;" + itemDonVi.sTenDonVi;
                            lstDONVI.Add(itemDonVi);
                            GetTreeDonViChild(itemDonVi.pk_iDonViID, strPrefix);
                        }
                    }
                }
            }
            catch (Exception ex) { }
            return lstDONVI;
        }

        public void GetTreeDonViChild(long ParentID, string strPrefixP)
        {
            var db = new RBACDataContext(_conn);
            string strPrefix = "";
            List<tbl_Donvi> lstDonViChild = null;
            lstDonViChild = (from dv_child in lstDONVITmp
                             where dv_child.iParent_ID == ParentID
                              && dv_child.Status == true
                             orderby dv_child.pk_iDonViID ascending
                             select dv_child).ToList<tbl_Donvi>();

            if (lstDonViChild != null && lstDonViChild.Count > 0)
            {
                int i = 0;
                foreach (tbl_Donvi itemChild in lstDonViChild)
                {
                    i += 1;
                    strPrefix = "";
                    strPrefix += "&nbsp;&nbsp;&nbsp;&nbsp;" + strPrefixP + "." + i + "";
                    itemChild.sTenDonVi = "<b style='color:red;'>" + strPrefix + ".</b>&nbsp;" + itemChild.sTenDonVi;
                    lstDONVI.Add(itemChild);
                    GetTreeDonViChild(itemChild.pk_iDonViID, strPrefix);
                }
            }
        }

        public long Insert(tbl_Donvi obj)
        {
            try
            {
                using (var trans = new TransactionScope())
                {
                    var db = new RBACDataContext(_conn);
                    db.tbl_Donvis.InsertOnSubmit(obj);
                    db.SubmitChanges();

                    trans.Complete();
                    return obj.pk_iDonViID;
                }
            }
            catch (Exception ex)
            {
            }
            return 0;
        }

        public long Update(tbl_Donvi entry)
        {
            try
            {
                using (var trans = new TransactionScope())
                {
                    var db = new RBACDataContext(_conn);

                    var obj = db.tbl_Donvis.SingleOrDefault(e => e.pk_iDonViID == entry.pk_iDonViID);
                    if (obj != null)
                    {
                        if (entry.iParent_ID != null || entry.iParent_ID != 0)
                        {
                            obj.iParent_ID = entry.iParent_ID;
                        }
                        obj.sMaDonVi = entry.sMaDonVi;
                        obj.sTenDonVi = entry.sTenDonVi;
                        obj.sDiaChi = entry.sDiaChi;
                        obj.sGhiChu = entry.sGhiChu;
                        obj.Status = entry.Status;
                        if (entry.sPath != null && entry.sPath != "" && entry.sPath != obj.sPath)
                        {
                            if (obj.sPath != null && obj.sPath != "")
                            {
                                List<tbl_Donvi> lstDonViCon = (from dv in db.tbl_Donvis
                                                               where (dv.sPath.Contains(obj.sPath) && dv.sPath != obj.sPath)
                                                               select dv).ToList<tbl_Donvi>();
                                foreach (tbl_Donvi dvc in lstDonViCon)
                                {
                                    dvc.sPath = dvc.sPath.Replace(obj.sPath, entry.sPath);
                                    db.SubmitChanges();
                                }
                            }
                            obj.sPath = entry.sPath;
                        }
                        db.SubmitChanges();
                    }
                    trans.Complete();
                    return 1;
                }
            }
            catch (Exception ex)
            {
                return 0;
            }
        }

        public DataTable GetIndentityIdDonvi(string _Table)
        {
            DataTable _dt = null;
            try
            {
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[1];
                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@Table";
                commandParameter[0].Value = _Table;
                if (commandParameter != null)
                {
                    _dt = SqlHelper.ExecuteDataset(_conn, "sp_GetIndentityIdDonVi", commandParameter).Tables[0];
                }
            }
            catch (Exception ex)
            {
            }
            return _dt;
        }

        public DataSet GetDonVi(string _name)
        {
            DataSet _dset = null;
            try
            {
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[1];
                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@Name";
                commandParameter[0].Value = _name;

                if (commandParameter != null)
                {
                    _dset = SqlHelper.ExecuteDataset(_conn, "GetDonVi", commandParameter);
                    string _dataLog = "";
                }
            }
            catch (Exception ex)
            {
            }

            return _dset;
        }

        public DataTable GetListNhanVien(long _lngDonviId)
        {
            DataTable _dt = null;
            try
            {
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[1];
                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@idonvi";
                commandParameter[0].Value = _lngDonviId;
                if (commandParameter != null)
                {
                    _dt = SqlHelper.ExecuteDataset(_conn, "sp_LayTatCaNhanVien", commandParameter).Tables[0];
                }
            }
            catch (Exception ex)
            {
            }
            return _dt;
        }

        public DataTable ListDonvi(long _lngDonviId)
        {
            DataTable _dt = null;
            try
            {
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[1];
                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@inDonViId";
                commandParameter[0].Value = _lngDonviId;
                if (commandParameter != null)
                {
                    _dt = SqlHelper.ExecuteDataset(_conn, "sp_LayTatCaDonVi", commandParameter).Tables[0];
                }
            }
            catch (Exception ex)
            {
            }
            return _dt;
        }

        public string GetListDonViCon(long _lngDonViChaID)
        {
            try
            {
                string strReturn = "";
                DataSet dts = null;
                DataTable dtbl = null;
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[1];

                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@inDonViId";
                commandParameter[0].Value = _lngDonViChaID;

                dts = SqlHelper.ExecuteDataset(_conn, "sp_LayTatCaDonVi", commandParameter);
                if (dts != null && dts.Tables.Count > 0)
                {
                    dtbl = dts.Tables[0];
                    if (dtbl != null && dtbl.Rows.Count > 0)
                    {
                        for (int i = 0; i < dtbl.Rows.Count - 1; ++i)
                        {
                            strReturn += dtbl.Rows[i]["pk_iDonViID"] + ", ";
                        }
                        strReturn += dtbl.Rows[dtbl.Rows.Count - 1]["pk_iDonViID"] + "";
                        dtbl = null;
                    }
                    dts = null;
                }
                return strReturn;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public DataSet GetDatasetDonViCha(long _lngDonViConID)
        {
            try
            {
                DataSet dts = null;
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[1];
                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@inDonViId";
                commandParameter[0].Value = _lngDonViConID;
                dts = SqlHelper.ExecuteDataset(_conn, "sp_LayTatCaDonViCha", commandParameter);
                return dts;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public List<tbl_Donvi> GetListDonViCha(long _lngDonViConID)
        {
            try
            {
                List<tbl_Donvi> lstRes = null;
                DataSet dts = null;
                DataTable dtbl = null;
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[1];
                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@inDonViId";
                commandParameter[0].Value = _lngDonViConID;

                dts = SqlHelper.ExecuteDataset(_conn, "sp_LayTatCaDonViCha", commandParameter);
                if (dts != null && dts.Tables.Count > 0)
                {
                    dtbl = dts.Tables[0];
                    if (dtbl != null && dtbl.Rows.Count > 0)
                    {
                        lstRes = new List<tbl_Donvi>();
                        tbl_Donvi objDonVi = null;
                        for (int i = 0; i < dtbl.Rows.Count; ++i)
                        {
                            objDonVi = new tbl_Donvi();
                            objDonVi.pk_iDonViID = long.Parse("0" + dtbl.Rows[i]["pk_iDonViID"]);
                            objDonVi.sTenDonVi = dtbl.Rows[i]["sTenDonVi"] + "";
                            objDonVi.iParent_ID = long.Parse("0" + dtbl.Rows[i]["iParent_ID"]);
                            objDonVi.sMaDonVi = dtbl.Rows[i]["sMaDonVi"] + "";
                            objDonVi.sDiaChi = dtbl.Rows[i]["sDiaChi"] + "";
                            objDonVi.sTenDonVi = dtbl.Rows[i]["sTenDonVi"] + "";
                            objDonVi.sGhiChu = dtbl.Rows[i]["sGhiChu"] + "";
                            objDonVi.Status = bool.Parse(dtbl.Rows[i]["Status"] + "");

                            lstRes.Add(objDonVi);
                        }
                        dtbl = null;
                    }
                    dts = null;
                }
                return lstRes;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public long Delete(long _id)
        {
            try
            {
                using (var trans = new TransactionScope())
                {
                    var db = new RBACDataContext(_conn);

                    tbl_Donvi obj = db.tbl_Donvis.FirstOrDefault<tbl_Donvi>(e => e.pk_iDonViID == _id);
                    if (obj != null)
                    {
                        obj.Status = false;
                        db.SubmitChanges();
                    }
                    trans.Complete();
                    db = null;
                    return 1;
                }
            }
            catch (Exception ex)
            {
                return 0;
            }
        }

        public tbl_Donvi SelectByID(long _idDonVi)
        {
            try
            {
                RBACDataContext db = new RBACDataContext(_conn);
                tbl_Donvi Res = (from m in db.tbl_Donvis
                                 where m.pk_iDonViID == _idDonVi
                                 && m.Status == true
                                 select m).FirstOrDefault<tbl_Donvi>();
                db = null;
                return Res;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public List<tbl_Donvi> lstDonViGen = null;
        /// <summary>
        /// Gen combobox Đơn vị
        /// </summary>
        /// <param name="_lngDonViID"></param>
        /// <returns></returns>
        public List<tbl_Donvi> GetTreeDonVi(long _lngDonViID)
        {
            tbl_Donvi objDonViCurrent = SelectByID(_lngDonViID);
            RBACDataContext db = new RBACDataContext(_conn);
            List<tbl_Donvi> lstRes = new List<tbl_Donvi>();
            lstDonViGen = new List<tbl_Donvi>();
            string strPrefix = "1";
            try
            {
                tbl_Donvi objDonViTemp = new tbl_Donvi();
                objDonViCurrent.sGhiChu = "<b class='red'>" + strPrefix + ".</b>&nbsp;" + objDonViCurrent.sTenDonVi;
                lstDonViGen.Add(objDonViCurrent);
                lstRes = (from m in db.tbl_Donvis
                          where m.Status == true
                          && m.iParent_ID == _lngDonViID
                          select m).ToList<tbl_Donvi>();
                if (lstRes != null && lstRes.Count > 0)
                {
                    for (int i = 0; i < lstRes.Count; i++)
                    {
                        GetTreeDonViForCombo(lstRes[i].pk_iDonViID, strPrefix, i + 1);
                    }
                }

            }
            catch (Exception ex)
            {
            }
            db = null;
            return lstDonViGen;
        }

        public void GetTreeDonViForCombo(long _lngDonViID, string _strPrefix, int _ilevel)
        {
            tbl_Donvi objDonVi = SelectByID(_lngDonViID);
            string strPrefix = "";
            try
            {
                strPrefix = _strPrefix + "." + _ilevel + "";
                objDonVi.sGhiChu = "<b class='red'>" + strPrefix + ".</b>&nbsp;" + objDonVi.sTenDonVi;
                lstDonViGen.Add(objDonVi);
                List<tbl_Donvi> lstDonViCon = new List<tbl_Donvi>();
                RBACDataContext db = new RBACDataContext(_conn);
                lstDonViCon = (from m in db.tbl_Donvis
                               where m.Status == true
                               && m.iParent_ID == _lngDonViID
                               select m).ToList<tbl_Donvi>();
                if (lstDonViCon != null && lstDonViCon.Count > 0)
                {
                    for (int i = 0; i < lstDonViCon.Count; i++)
                    {
                        GetTreeDonViForCombo(lstDonViCon[i].pk_iDonViID, strPrefix, i + 1);
                    }
                }
                db = null;
            }
            catch (Exception ex)
            {
            }
        }

        public tbl_Donvi LayDonViGoc()
        {
            try
            {
                using (var trans = new TransactionScope())
                {
                    RBACDataContext db = new RBACDataContext(_conn);
                    tbl_Donvi donvi = db.tbl_Donvis.FirstOrDefault(m => m.iParent_ID == null);
                    db = null;
                    return donvi;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public bool CheckDonViChaCon(long iddonviCha, long iddonviCon)
        {
            RBACDataContext db = new RBACDataContext(_conn);
            tbl_Donvi objDonvicha = SelectByID(iddonviCha);
            tbl_Donvi objDonvicon = SelectByID(iddonviCon);

            if (objDonvicha.sPath.Contains(objDonvicon.sPath))
            {
                return true;
            }
            else
                return false;
        }

        /// <summary>
        /// Cap nhat lai spath cho don vi them moi
        /// </summary>
        /// <param name="_entry"></param>
        public void UpdateSpath(tbl_Donvi _entry)
        {
            RBACDataContext db = new RBACDataContext(_conn);
            try
            {
                tbl_Donvi dv = (from dvs in db.tbl_Donvis
                                where dvs.pk_iDonViID == _entry.pk_iDonViID
                                select dvs).FirstOrDefault<tbl_Donvi>();
                dv.sPath = _entry.sPath;
                db.SubmitChanges();
            }
            catch (Exception ex)
            {
            }
        }

        //Chọn đơn vị người dùng quản lý
        public List<tbl_Donvi> GetOrgDepartments(long _iUserID)
        {
            List<tbl_Donvi> lstRes = new List<tbl_Donvi>();
            RBACDataContext db = new RBACDataContext(_conn);
            var objVTNDDV = from m in db.tbl_VaiTroNguoiDungDonVis
                            where m.bKichHoat == true
                            && m.fk_iNguoiDungID == _iUserID
                            select m;
            string tes = "";
            foreach (tbl_VaiTroNguoiDungDonVi n in objVTNDDV)
            {
                tbl_Donvi objDV = (from c in db.tbl_Donvis
                                   where c.Status == true
                                   && c.pk_iDonViID == n.fk_iDonViID
                                   select c).FirstOrDefault<tbl_Donvi>();
                if (objDV != null && objDV.sTenDonVi != tes)
                {
                    lstRes.Add(objDV);
                    tes = objDV.sTenDonVi;
                }
            }

            return lstRes;
        }

        public List<tbl_Donvi> ShowListDonVi(long _idDonViThaoTac)
        {
            tbl_Donvi objDonViCurrent = SelectByID(_idDonViThaoTac);
            RBACDataContext db = new RBACDataContext(_conn);
            List<tbl_Donvi> lstRes = new List<tbl_Donvi>();
            lstDonViGen = new List<tbl_Donvi>();
            string strPrefix = "";
            try
            {
                tbl_Donvi objDonViTemp = new tbl_Donvi();
                objDonViCurrent.sTenDonVi = strPrefix + objDonViCurrent.sTenDonVi;
                lstDonViGen.Add(objDonViCurrent);
                lstRes = (from m in db.tbl_Donvis
                          where m.Status == true
                          && m.iParent_ID == _idDonViThaoTac
                          select m).ToList<tbl_Donvi>();
                if (lstRes != null && lstRes.Count > 0)
                {
                    for (int i = 0; i < lstRes.Count; i++)
                    {
                        ShowTreeDonViForCombo(lstRes[i].pk_iDonViID, strPrefix, i + 1);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            db = null;
            return lstDonViGen;
        }

        public void ShowTreeDonViForCombo(long _lngDonViId, string _strPrefix, int _iThuTu)
        {
            tbl_Donvi objDonVi = SelectByID(_lngDonViId);
            string strPrefix = "";
            try
            {
                strPrefix = _strPrefix + "&nbsp;&nbsp;";
                objDonVi.sTenDonVi = strPrefix + objDonVi.sTenDonVi;
                lstDonViGen.Add(objDonVi);
                List<tbl_Donvi> lstDonViCon = new List<tbl_Donvi>();
                RBACDataContext db = new RBACDataContext(_conn);
                lstDonViCon = (from m in db.tbl_Donvis
                               where m.Status == true
                               && m.iParent_ID == _lngDonViId
                               select m).ToList<tbl_Donvi>();
                if (lstDonViCon != null && lstDonViCon.Count > 0)
                {
                    for (int i = 0; i < lstDonViCon.Count; i++)
                    {
                        ShowTreeDonViForCombo(lstDonViCon[i].pk_iDonViID, strPrefix, i + 1);
                    }
                }
                db = null;
            }
            catch (Exception ex)
            {
            }
        }
    }
}
